package cn.bo.cloud.common.core.utils.image;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.*;
import java.util.Base64;
/**
 * @ClassName Base64ImgUtil
 * @Description TODO
 * @Author jb.zhou
 * @Date 2020/11/20
 * @Version 1.0
 */
public class Base64ImgUtil {
    private static final Logger logger = LoggerFactory.getLogger(Base64ImgUtil.class);

    public final static String SEPARATOR = File.separator;
    public static final String FILE_TMP_PATH = "tmp";


    //图片转化成base64字符串
    public static String GetImageStrFull(String filePath) {
        String suffix = getSuffix(filePath);
        String base64 = GetImageStr(filePath);
        if (StringUtils.isNotBlank(base64)) {
           return "data:image/"+suffix+";base64," + base64;
        }
        return null;
    }
    public static String GetImageStr(String filePath) {
        File file = new File(filePath);
        return GetImageStr(file);
    }

    public static String GetImageStr(File imgFile) {
        String base64 = null;
        try (InputStream in = new FileInputStream(imgFile);) {
            return GetImageStr(in, imgFile.length());
        } catch (IOException e) {
            logger.info("Base64ImgUtil GetImageStr e:" + e.getMessage());
        }
        return base64;
    }

    public static String GetImageStr(InputStream in, long fileLength) {
        String base64 = null;
        try {
            // 该实现需要注意文件大小，长度超过数组限制会报错
            byte[] bytes = new byte[(int)fileLength];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            logger.info("Base64ImgUtil GetImageStr e:" + e.getMessage());
        }
        return base64;
    }

    public static String GetImageStr(byte[] bytes) {
        String base64 = null;
        base64 = Base64.getEncoder().encodeToString(bytes);
        return base64;
    }

    //base64字符串转化成图片
    public static String GenerateImage(String imgBase64, String fileName, String outPath) {
        Assert.hasLength(imgBase64, "Base64Img文件不能为空");
        Assert.hasLength(fileName, "Base64Img文件名称不能为空");
        Assert.hasLength(outPath, "Base64Img文件输出路径不能为空");
        //对字节数组字符串进行Base64解码并生成图片
        String imgPath = outPath + SEPARATOR + FILE_TMP_PATH;
        //文件目录不存在则创建
        File outFile = new File(imgPath);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }

        //Base64解码
        byte[] b = Base64.getDecoder().decode(imgBase64);
        for (int i = 0; i < b.length; ++i) {
            //调整异常数据
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        //新生成的图片
        //这种写法不需要flush或者close 会自动关闭 FileOutputStream 实现了java中的java.lang.AutoCloseable接口。
        try (OutputStream out = new FileOutputStream(imgPath + SEPARATOR + fileName)) {
            out.write(b);
            return imgPath + SEPARATOR + fileName;
        } catch (Exception e) {
            logger.info("Base64Util GenerateImage e:{}", e.getMessage());
        }
        return "";
    }

    private static String getSuffix(String fileName) {
        if (fileName.contains(".")) {
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
            return suffix.toLowerCase();
        }
        return "";
    }
}
